package com.sssre.lttcloud.codegen.controller;

import com.sssre.lttcloud.codegen.entity.TableInfo;
import com.sssre.lttcloud.codegen.service.CodeGenService;
import com.sssre.lttcloud.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 代码生成控制器
 */
@RestController
@RequestMapping("/codegen")
@CrossOrigin
public class CodeGenController {

    @Autowired
    private CodeGenService codeGenService;

    /**
     * 获取数据库表列表
     */
    @GetMapping("/tables")
    public Result getTableList() {
        return codeGenService.getTableList();
    }

    /**
     * 获取表字段信息
     */
    @GetMapping("/columns/{tableName}")
    public Result getTableColumns(@PathVariable String tableName) {
        return codeGenService.getTableColumns(tableName);
    }

    /**
     * 预览代码
     */
    @PostMapping("/preview")
    public Result previewCode(@Valid @RequestBody TableInfo tableInfo) {
        return codeGenService.previewCode(tableInfo);
    }

    /**
     * 生成代码
     */
    @PostMapping("/generate")
    public Result generateCode(@Valid @RequestBody TableInfo tableInfo) {
        return codeGenService.generateCode(tableInfo);
    }

    /**
     * 下载代码
     */
    @PostMapping("/download")
    public ResponseEntity<byte[]> downloadCode(@Valid @RequestBody TableInfo tableInfo) {
        Result<byte[]> result = codeGenService.downloadCode(tableInfo);
        
        if (result.isSuccess()) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", 
                tableInfo.getClassName() + "_code.zip");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(result.getData());
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
} 